﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Data.Core.Models;
using Data.Core;
using System.Data.Entity;

namespace Data.Service
{
    public class BlogService : IBlogService
    {
        public void Delete(Blog blog)
        {
            if(blog == null)
            {
                throw new ArgumentNullException("blog");
            }
            using (var db = new BloggingContext())
            {
                db.Set<Blog>().Attach(blog);
                db.Entry<Blog>(blog).State = EntityState.Deleted;
                db.SaveChanges();
            }
        }

        public IList<Blog> GetAllBlogs()
        {
            using (var db = new BloggingContext())
            {
                var list = db.Blogs.ToList();
                return list.ToList();
            }
        }

        public void Insert(Blog blog)
        {
            if (blog == null)
            {
                throw new ArgumentNullException("blog");
            }
            using (var db = new BloggingContext())
            {
                db.Blogs.Add(blog);
                db.SaveChanges();
            }
        }

        public void Update(Blog blog)
        {
            if (blog == null)
            {
                throw new ArgumentNullException("blog");
            }
            using (var db = new BloggingContext())
            {
                db.Set<Blog>().Attach(blog);
                db.Entry<Blog>(blog).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        public Blog GetBlogById(int id)
        {
            if(id == 0)
            {
                throw new ArgumentNullException("id");
            }
            using (var db = new BloggingContext())
            {
                return db.Blogs.Find(id);
            }
        }
    }
}
